package com.wee.aircoach_user;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.bigtotoro.util.DeviceUtil;
import com.bigtotoro.util.SharedPreferencesUtil;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.chatuidemo.DemoHXSDKHelper;
import com.easemob.chatuidemo.db.UserDao;
import com.easemob.chatuidemo.domain.User;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wee.entity.MD5Util;
import com.wee.entity.UserLogin;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class  WelcomeActivity extends Activity {
    private static final int MSG_WELCOME = 1;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==MSG_WELCOME){
                //startActivity(new Intent(WelcomeActivity.this,MainActivity.class));
                SharedPreferencesUtil.setInt(WelcomeActivity.this, Constant.USERTIME, 0);
         //    getVersion();
             getUserId();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mHandler.sendEmptyMessage(MSG_WELCOME);
            }
        }).start();
    }

    private void getUserId() {
        /** 解析字段 */
       int a=  SharedPreferencesUtil.getInt(WelcomeActivity.this,Constant.USERTIME);
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, Constant.GET_USERID_BY_UUID+MD5Util.md5(a)+"&uuid="+ (DeviceUtil.getUUID(this)+5), new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String str = responseInfo.result;
                Gson gs = new Gson();
                JsonObject jo = gs.fromJson(str, JsonObject.class);
                JsonElement je = jo.get("status");
                String status = je.getAsString();
                if ("ok".equals(status)) {
                    JsonObject object = jo.getAsJsonObject("data");
                    UserLogin list1 = gs.fromJson(object, UserLogin.class);
                    SharedPreferencesUtil.setInt(WelcomeActivity.this, Constant.USERID, Integer.parseInt(list1.getId()));
                    loginHX("user_" + list1.getId());
                }else {
                    try{
                        JsonElement je1 = jo.get("data");
                        String data= je1.getAsString();
                    if("err token.".equals(data)){
                        JsonElement je2 = jo.get("time");
                        String time= je2.getAsString();
                        long aa=Long.parseLong(time);
                        long bb=Math.round(new Date().getTime() / 1000);
                        long cc=aa-bb;
                        SharedPreferencesUtil.setInt(WelcomeActivity.this, Constant.USERTIME, (int) cc);
                        getUserId();
                    }else{
                        startActivity(new Intent(WelcomeActivity.this, RegisterActivity.class));
                        finish();
                    }
                    }catch (Exception r){

                    }
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                System.out.println(e.getMessage());
            }
        });



}
    private void loginHX(final String user){
        EMChatManager.getInstance().login(user, Constant.HX_PWD, new EMCallBack() {

            @Override
            public void onSuccess() {

                // 登陆成功，保存用户名密码
                MyApplication.getInstance().setUserName(user);
                MyApplication.getInstance().setPassword(Constant.HX_PWD);

                try {
                    // ** 第一次登录或者之前logout后再登录，加载所有本地群和回话
                    // ** manually load all local groups and
                    EMGroupManager.getInstance().loadAllGroups();
                    EMChatManager.getInstance().loadAllConversations();
                    // 处理好友和群组
                    initializeContacts();
                } catch (Exception e) {
                    e.printStackTrace();
                    // 取好友或者群聊失败，不让进入主页面
                    runOnUiThread(new Runnable() {
                        public void run() {
                            DemoHXSDKHelper.getInstance().logout(null);
                            Toast.makeText(WelcomeActivity.this.getApplicationContext(), R.string.login_failure_failed, Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                }
                // 更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
                boolean updatenick = EMChatManager.getInstance().updateCurrentUserNick(
                        MyApplication.currentUserNick.trim());
                if (!updatenick) {
                    Log.e("LoginActivity", "update current user nick fail");
                }
                startActivity(new Intent(WelcomeActivity.this,MainActivity.class));
                finish();

            }

            @Override
            public void onProgress(int arg0, String arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onError(int arg0, final String arg1) {
                // TODO Auto-generated method stub
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(), "" + arg1, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void initializeContacts() {
        Map<String, User> userlist = new HashMap<String, User>();
        // 添加user"申请与通知"
        User newFriends = new User();
        newFriends.setUsername(com.easemob.chatuidemo.Constant.NEW_FRIENDS_USERNAME);
        String strChat = getResources().getString(
                R.string.Application_and_notify);
        newFriends.setNick(strChat);

        userlist.put(com.easemob.chatuidemo.Constant.NEW_FRIENDS_USERNAME, newFriends);
        // 添加"群聊"
        User groupUser = new User();
        String strGroup = getResources().getString(R.string.group_chat);
        groupUser.setUsername(com.easemob.chatuidemo.Constant.GROUP_USERNAME);
        groupUser.setNick(strGroup);
        groupUser.setHeader("");
        userlist.put(com.easemob.chatuidemo.Constant.GROUP_USERNAME, groupUser);

        // 添加"Robot"
        User robotUser = new User();
        String strRobot = getResources().getString(R.string.robot_chat);
        robotUser.setUsername(com.easemob.chatuidemo.Constant.CHAT_ROBOT);
        robotUser.setNick(strRobot);
        robotUser.setHeader("");
        userlist.put(com.easemob.chatuidemo.Constant.CHAT_ROBOT, robotUser);

//        // 存入内存
//        DemoHXSDKHelper.getInstance().setc
//        ((DemoHXSDKHelper) HXSDKHelper.getInstance()).setContactList(userlist);
        // 存入db
        UserDao dao = new UserDao(this);
        List<User> users = new ArrayList<User>(userlist.values());
        dao.saveContactList(users);
    }


}
